package com.icss.id.service.Impl;

import com.icss.id.dao.IRecordDao;
import com.icss.id.dao.UserDao;
import com.icss.id.pojo.User;
import com.icss.id.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

import java.util.List;



@Component
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private IRecordDao iRecordDao;


    public List findUser(){
        List<User> all = userDao.findAll();
        return all;
    }

    /**
     * 查询用户并按照为处理数排序
     * @return
     */
    public List<User> findUserDescUn() {
        Sort sort = Sort.by(Sort.Direction.DESC, "unDoViolationCount");
        List<User> all = userDao.findAll(sort);
        return all;
    }

    /**
     * 处理事件
     *
     * @param fine
     * @param score
     * @return
     */
    public void updateUser(Integer fine, Integer score, Integer recordId) {
        User body = iRecordDao.findById(recordId).get().getUser();

        if (body != null) {
            if (body.getAccount() >= fine) {
                body.setAccount(body.getAccount() - fine);
            } else {
                body.setAccount(0.0);
            }

            if (12 - score >= 0) {
                body.setAvailableScore(12 - score);
            } else {
                body.setAvailableScore(0);
            }
            if(body.getUnDoViolationCount() - 1>=0){
                body.setUnDoViolationCount(body.getUnDoViolationCount() - 1);
            }else{
                body.setUnDoViolationCount(0);
            }
            body.setViolationCount(body.getViolationCount() + 1);

            User save = userDao.save(body);

            if(save!=null){
                iRecordDao.updateStatus(true,save,recordId);
            }

        }

    }

    @Override
    public User findUserName(String username) {
        User user = userDao.findByUserName(username);
        return user;
    }


}
